import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import { urlConfigs } from './config';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

import * as moment from 'moment';
declare const MD5;

@Injectable()
export class SignService {

    constructor(private http: Http) { }

    // 获取用户当月签到情况
    getCheckInMonth(openid: string): Promise<any> {
        let headers = new Headers();
        headers.append('openid', openid);
        return this.http.get(urlConfigs.checkined + '?' + this.encrypt(openid), { headers: headers })
            .toPromise()
            .then(res => res.json().data)
            .catch(this.handleError);
    };

    // 进行签到
    checkIn(openid: string): Promise<any> {
        let headers = new Headers();
        headers.append('openid', openid);
        return this.http.put(urlConfigs.checkin + '?' + this.encrypt(openid), {}, { headers: headers })
            .toPromise()
            .then(res => res.json().code)
            .catch(this.handleError);
    };

    // 处理请求出错
    handleError(error: any): Promise<any> {
        alert('程序请求出错');
        return Promise.reject(error.message || error);
    };

    // MD5加密处理encrypt
    encrypt(openid: string) {
        // 获取时间戳
        let timeUnix = moment().valueOf().toString();

        // 加密key
        let key = timeUnix.substring(0, 3) + timeUnix.substring(10);

        // 数组形式缓存两个参数
        let paramString = ['openid=' + openid, 't=' + timeUnix];

        // ASCII码排序
        paramString.sort();

        // openid=abcd1s5a5ss&t=1318874398&key=131398
        let paramKey = paramString.join('&') + '&key=' + key;

        // MD5加密
        let encryptResult = MD5(paramKey).toUpperCase();

        // key=abcdefs&t=1318874398
        let requestQuery = 'key=' + encryptResult + '&t=' + timeUnix;

        return requestQuery;
    }
}
